package com.sensetime.jv.service.impl;

import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.sensetime.jv.entity.UserRolesJv;
import com.sensetime.jv.mapper.UserRolesMapper;
import com.sensetime.jv.service.AuthService;
import com.sensetime.jv.service.UserRoleCacheService;
import com.sensetime.jv.util.RedisCache;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Objects;

@Slf4j
@Service
public class UserRoleCacheServiceImpl implements UserRoleCacheService {

    

    @Resource
    private UserRolesMapper userRolesMapper;

    
    @Resource
    private AuthService authService;

    @Resource
    private RedisCache redisCache;

    @Value("${redis.cache.custom.tokenKey}")
    // Redis键前缀（避免键冲突）
    private String TOKEN_PREFIX;       // 存储Token：token:user:{userId} -> token值



    /**
     * 更新用户缓存里的角色信息
     *
     * @param roleId
     */
    @Override
    public void updateUserRole(Integer roleId) {
        List<UserRolesJv> list = new LambdaQueryChainWrapper<>(userRolesMapper).eq(UserRolesJv::getRoleId, roleId).list();
        if (list.isEmpty()) return;
        Map<String, Object> userTokenList = redisCache.getKeysAndValuesByPrefix(TOKEN_PREFIX);

        for (UserRolesJv userRolesJv : list) {
            Object object = userTokenList.get(TOKEN_PREFIX + userRolesJv.getUserId());
            if (Objects.isNull(object)) continue;
            authService.getUserInfo(userRolesJv.getUserId(), String.valueOf(object));

        }
    }
}
